<template>
  <div class="main">
    <div>
      <el-input v-model="keyword" placeholder="用户名" style="width: 200px; margin-right: 10px"></el-input>
      <el-button type="primary" icon="el-icon-search" @click="getSearch">搜索</el-button>
      <el-button @click="clear">清空</el-button>
    </div>
    <div style="margin-top: 10px">
      <el-button type="primary" @click="showAdd">添加</el-button>
      <el-button type="danger" @click="revomveRoles">批量删除</el-button>
    </div>

    <!-- //添加表单弹出框 -->
    <el-dialog :title="form.id ? '修改角色' : '添加角色'" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="ruleForm" v-loading="loading">
        <el-form-item label="角色名称" label-width="100px" prop="roleName">
          <el-input v-model="form.roleName"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRoleOrUpdate('ruleForm')">
          {{
          !form.id ? "添 加" : "修 改"
          }}
        </el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-table
      ref="multipleTable"
      tooltip-effect="dark"
      style="margin-top: 10px"
      @selection-change="handleSelectionChange"
      border
      :data="roles"
    >
      <el-table-column align="center" type="selection" width="55"></el-table-column>
      <el-table-column align="center" type="index" label="序号" width="100"></el-table-column>
      <el-table-column label="角色名称" width="width">
        <template slot-scope="{ row }">
          <span v-show="!row.edit">{{ row.roleName }}</span>
          <el-input
            v-model="row.roleName"
            v-show="row.edit"
            style="width: 200px; margin-right: 10px"
            size="mini"
            :ref="row.id"
            @blur="update(row)"
          ></el-input>
          <!-- <el-button
            type="warning"
            v-show="row.edit"
            @click="row.edit = false"
            size="mini"
            >取消</el-button
          >-->
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row }">
          <el-button type="info" icon="el-icon-user" size="mini" @click="goRoleTree(row.id)"></el-button>
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRole(row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      align="center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[3, 5, 7, 9]"
      :page-size="size"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  name: "Role",
  data() {
    var validateName = (rule, value, callback) => {
      if (value.length < 3) {
        return callback(new Error("角色名至少3个字符"));
      }
      callback();
    };
    return {
      keyword: "",
      search: {},
      multipleSelection: [],
      page: 1,
      size: 5,
      total: 0,
      roles: [],
      dialogFormVisible: false,
      form: {
        roleName: ""
      },
      loading: false,
      rules: {
        roleName: [
          { required: true, message: "角色名必须输入" },
          { validator: validateName, trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    this.getRole();
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //分页操作
    handleSizeChange(val) {
      (this.size = val), this.getRole();
    },
    handleCurrentChange(val) {
      (this.page = val), this.getRole();
    },

    //获取用户列表
    async getRole() {
      let result = await this.$api.default.role.getRoles(
        this.page,
        this.size,
        this.search
      );
      if (result.code == 20000) {
        this.roles = result.data.items;
        this.total = result.data.total;
      }
    },
    //搜索
    getSearch() {
      this.search.roleName = this.keyword;
      this.getRole();
    },
    //清空搜索框
    clear() {
      this.keyword = "";
      this.search.roleName = "";
      this.getRole();
    },

    //打开添加角色界面
    showAdd() {
      this.loading = false;
      this.dialogFormVisible = true;
      this.form = {};
      this.$nextTick(() => this.$refs.ruleForm.clearValidate());
    },

    //添加角色||修改角色
    addRoleOrUpdate(ruleForm) {
      this.$refs[ruleForm].validate(async valid => {
        try {
          if (valid) {
            this.loading = true;
            let result = await this.$api.default.role[
              !this.form.id ? "addRole" : "updateRole"
            ](this.form);
            if (result.code == 20000) {
              this.loading = false;
              this.getRole();
              this.dialogFormVisible = false;
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            }
            this.form = {};
          } else {
            this.$message({
              type: "danger",
              message: "操作失败!"
            });
            return false;
          }
        } catch (error) {
          this.loading = false;
          this.$message({
            type: "info",
            message: "名字重复,请重新重试!"
          });
          return;
        }
      });
    },

    revomveRoles() {
      this.$confirm("确定删除吗?", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning"
      })
        .then(async () => {
          let multipleSelection = this.multipleSelection.map(item => {
            return item.id;
          });
          if (multipleSelection.length <= 0) {
            throw new Error();
          }
          let result = await this.$api.default.role.batchRemove(
            multipleSelection
          );
          this.getRole();
          this.$message.success("删除成功");
        })
        .then(result => {})
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    async delRole(id) {
      let result = await this.$api.default.role.delRole(id);
      if (result.code == 20000) {
        this.$message.success("删除成功");
        this.getRole();
      }
    },

    edit(row) {
      this.$set(row, "edit", true);
      this.$nextTick(() => {
        this.$refs[row.id].focus();
      });
    },
    async update(row) {
      let result = await this.$api.default.role.updateRole(row);
      if (result.code == 20000) {
        this.getRole();
        this.$message.success("操作成功");
      }
      row.edit = false;
    },

    //去权限管理
    goRoleTree(id) {
      this.$router.push({
        name: "RoleTree",
        params: {
          id
        }
      });
    }
  }
};
</script>

<style>
.main {
  padding: 20px;
}
</style>